package com.example.demo.action;

import com.example.demo.dao.*;
import com.example.demo.model.*;
import com.example.demo.util.Pager;
import com.example.demo.util.Util;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@Controller
public class IndexAction extends ActionSupport {

	private static final long serialVersionUID = -4304509122548259589L;

	private String url = "./";

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	// 获取请求对象
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ServletActionContext.getRequest();
		return request;
	}

	// 获取响应对象
	public HttpServletResponse getResponse() {
		HttpServletResponse response = ServletActionContext.getResponse();
		return response;
	}

	// 获取session对象
	public HttpSession getSession() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		return session;
	}

	// 获取输出对象
	public PrintWriter getPrintWriter() {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return writer;
	}

	@Autowired
	private ZhutiDao zhutiDao;
	
	
	public ZhutiDao getZhutiDao() {
		return zhutiDao;
	}

	public void setZhutiDao(ZhutiDao zhutiDao) {
		this.zhutiDao = zhutiDao;
	}

	@Autowired
	private RenDao renDao;

	public RenDao getRenDao() {
		return renDao;
	}

	public void setRenDao(RenDao renDao) {
		this.renDao = renDao;
	}

	
	
	// 网站首页
	public String index() throws Exception {
		HttpServletRequest request = this.getRequest();
		request.setAttribute("list", zhutiDao.selectBeanList(0, 8, " where deletestatus=0 order by id desc  "));
		return SUCCESS;
	}
	
	
	//跳转到查看投票页面
	public String toupiao() {
		HttpServletRequest request = this.getRequest();
		Zhuti bean = zhutiDao.selectBean(" where id= "+ request.getParameter("id"));
		
		zhutiDao.updateBean(bean);
		
		
		List<Ren> list = renDao.selectBeanList(0, 9999, " where  deletestatus=0 and  zhuti.id= "+bean.getId());
		
		request.setAttribute("list", list);
		

		request.setAttribute("bean", bean);
		this.setUrl("toupiao.jsp");
		return SUCCESS;
	}
	
	
	//跳转到查看投票详情页面
	public String xiangqing() {
		HttpServletRequest request = this.getRequest();
		Zhuti bean = zhutiDao.selectBean(" where id= "+ request.getParameter("id"));
		
		zhutiDao.updateBean(bean);
		
		
		request.setAttribute("bean", bean);
		this.setUrl("xiangqing.jsp");
		return SUCCESS;
	}
	
	
	//在线投票列表
	public String pinxuan() throws Exception {

		HttpServletRequest request = this.getRequest();

		StringBuffer sb = new StringBuffer();
		sb.append(" where ");

		
		
		sb.append("  deletestatus=0  order by id desc ");
	
		
		String where = sb.toString();


		int currentpage = 1;
		int pagesize = 10;
		if (request.getParameter("pagenum") != null) {
			currentpage = Integer.parseInt(request.getParameter("pagenum"));
		}
		
		int total = zhutiDao.selectBeanCount(where.replaceAll("order by id desc", ""));
		
		request.setAttribute("zhutilist", zhutiDao.selectBeanList((currentpage - 1)* pagesize, pagesize, where));
		
		request.setAttribute("pagerinfo", Pager.getPagerNormal(total, pagesize,currentpage, "indexmethod!pinxuan", "共有" + total + "条记录"));

		this.setUrl("pinxuan.jsp");
		return SUCCESS;
	}

	@Autowired
	private GonggaoDao gonggaoDao;

	public GonggaoDao getGonggaoDao() {
		return gonggaoDao;
	}

	public void setGonggaoDao(GonggaoDao gonggaoDao) {
		this.gonggaoDao = gonggaoDao;
	}

	
	
	
	//通知公告列表
	public String list() throws Exception {

		HttpServletRequest request = this.getRequest();

		StringBuffer sb = new StringBuffer();
		sb.append(" where ");

		
		
		sb.append("  deletestatus=0  order by id desc ");
	
		
		String where = sb.toString();


		int currentpage = 1;
		int pagesize = 10;
		if (request.getParameter("pagenum") != null) {
			currentpage = Integer.parseInt(request.getParameter("pagenum"));
		}
		
		int total = gonggaoDao.selectBeanCount(where.replaceAll("order by id desc", ""));
		
		request.setAttribute("gonggaolist", gonggaoDao.selectBeanList((currentpage - 1)* pagesize, pagesize, where));
		
		request.setAttribute("pagerinfo", Pager.getPagerNormal(total, pagesize,currentpage, "indexmethod!list", "共有" + total + "条记录"));

		this.setUrl("list.jsp");
		return SUCCESS;
	}
	
	
	
	//跳转到查看通知公告详情页面
	public String detail() {
		HttpServletRequest request = this.getRequest();
		Gonggao bean = gonggaoDao.selectBean(" where id= "+ request.getParameter("id"));
		
		gonggaoDao.updateBean(bean);
		
		
		request.setAttribute("bean", bean);
		this.setUrl("detail.jsp");
		return SUCCESS;
	}

	@Autowired
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	
	
	//用户注册操作
	public void register() throws IOException {
		HttpServletRequest request = this.getRequest();

		PrintWriter writer = this.getPrintWriter();

		String dianhua = request.getParameter("dianhua");
		String password = request.getParameter("password");
		String username = request.getParameter("username");
		
		User bean = userDao.selectBean(" where deletestatus=0 and username='"+ username + "' ");
		if (bean == null) {
			bean = new User();
			bean.setCreatetime(Util.getTime());
			bean.setDianhua(dianhua);
			bean.setPassword(password);
			bean.setRole(1);
			bean.setUsername(username);
			userDao.insertBean(bean);
			writer
					.print("<script language=javascript>alert('注册成功');window.location.href='login.jsp';</script>");
		} else {
			writer
					.print("<script language=javascript>alert('注册失败，该用户名已经存在');window.location.href='reg.jsp';</script>");
		}

	}

	

	// 登录操作
	public void login() throws IOException {
		HttpServletRequest request = this.getRequest();

		PrintWriter writer = this.getPrintWriter();

		String username = request.getParameter("username");
		String password = request.getParameter("password");

		User bean = userDao.selectBean(" where username = '" + username+ "' and password= '" + password+ "' and deletestatus=0 and role!=0 ");

		if (bean != null) {
			HttpSession session = request.getSession();
			session.setAttribute("qiantai", bean);

			writer
					.print("<script language=javascript>alert('登录成功');window.location.href='.';</script>");
		} else {
			writer
					.print("<script language=javascript>alert('用户名或者密码错误');window.location.href='.';</script>");
		}

	}

	// 用户退出
	public void loginout() throws IOException {
		HttpServletRequest request =  this.getRequest();
		PrintWriter writer = this.getPrintWriter();	
		HttpSession session = request.getSession();
		session.removeAttribute("qiantai");
		writer.print("<script language=javascript>alert('退出成功');window.location.href='.';</script>");
	}
	
	
	
	// 跳转到修改个人密码页面
	public String userupdate3() {
		HttpServletRequest request = this.getRequest();
		request.setAttribute("url", "indexmethod!userupdate4");
		request.setAttribute("title", "修改密码");
		this.setUrl("userupdate3.jsp");
		return SUCCESS;
	}

	//修改个人密码操作
	public void userupdate4() throws IOException {
		HttpServletRequest request = this.getRequest();

		PrintWriter writer = this.getPrintWriter();
		
		HttpSession session = request.getSession();
		User uu = (User)session.getAttribute("qiantai");

		String password1 = request.getParameter("password1");
		String password2 = request.getParameter("password2");
	

		User bean = userDao.selectBean(" where deletestatus=0 and username='"+uu.getUsername()+"'  and password='"+password1+"'");
		
		if(bean!=null){
			bean.setPassword(password2);
			userDao.updateBean(bean);
			writer
					.print("<script language=javascript>alert('修改成功');window.location.href='indexmethod!userupdate3';</script>");
		}else{
			writer
			.print("<script language=javascript>alert('修改失败，原密码错误');window.location.href='indexmethod!userupdate3';</script>");
		}
		
		

	}

	@Autowired
	private ToupiaoDao toupiaoDao;

	public ToupiaoDao getToupiaoDao() {
		return toupiaoDao;
	}

	public void setToupiaoDao(ToupiaoDao toupiaoDao) {
		this.toupiaoDao = toupiaoDao;
	}
	
	

	//用户投票操作
	public void tp() throws IOException {
		HttpServletRequest request = this.getRequest();

		PrintWriter writer = this.getPrintWriter();
		
		HttpSession session = request.getSession();
		User uu = (User)session.getAttribute("qiantai");
		
		if(uu==null){
			writer.print("<script language=javascript>alert('请先登录');window.location.href='login.jsp';</script>");
			return  ;
		}
		
		String renid = request.getParameter("renid");
		
		Ren ren = renDao.selectBean(" where id= "+renid);
		
		String stime = ren.getZhuti().getStime();
		
		String etime = ren.getZhuti().getEtime();
		
		String now =Util.getRiqi();
		
		int s1 = Integer.parseInt(stime.replaceAll("-", ""));
		
		int e1 = Integer.parseInt(etime.replaceAll("-", ""));
		
		int n = Integer.parseInt(now.replaceAll("-", ""));
		
		if(n<s1){
			writer.print("<script language=javascript>alert('投票还未开始');window.location.href='indexmethod!toupiao?id="+ren.getZhuti().getId()+"';</script>");
			return ;
		}


		if(n>e1){
			writer.print("<script language=javascript>alert('投票已经结束');window.location.href='.';</script>");
			return ;
		}
		
		
		
		Toupiao bean = toupiaoDao.selectBean(" where user.id="+uu.getId()+" and ren.zhuti.id="+ren.getZhuti().getId()+" ");
		
		if(bean!=null){
			writer.print("<script language=javascript>alert('您已经参加了评选，请勿重复投票');window.location.href='indexmethod!toupiao?id="+bean.getRen().getZhuti().getId()+"';</script>");
			return ;
		}
		
		
		
		
		bean = new Toupiao();
		
		bean.setCtime(Util.getTime());
		bean.setRen(ren);
		bean.setUser(uu);
		

		toupiaoDao.insertBean(bean);
		
		ren.setShu(ren.getShu()+1);
		
		
		renDao.updateBean(ren);
		
		
		writer.print("<script language=javascript>alert('投票成功');window.location.href='indexmethod!renlist3?zid="+bean.getRen().getZhuti().getId()+"';</script>");
		
		

	}
	
	
	//跳转到简介页面
	public String renshow() {
		HttpServletRequest request = this.getRequest();
		
		
		Ren bean = renDao.selectBean(" where id= "+request.getParameter("id"));
		
		
		request.setAttribute("bean", bean);
		
	
		this.setUrl("ren.jsp");
		return SUCCESS;
	}
	
	
	
	//投票记录列表
	public String toupiaolist() throws Exception {

		HttpServletRequest request = this.getRequest();

		StringBuffer sb = new StringBuffer();
		sb.append(" where ");

		HttpSession session = request.getSession();
		User uu = (User)session.getAttribute("qiantai");
		
		sb.append("  deletestatus=0 and user.id="+uu.getId()+"  order by id desc ");
	
		
		String where = sb.toString();


		int currentpage = 1;
		int pagesize = 10;
		if (request.getParameter("pagenum") != null) {
			currentpage = Integer.parseInt(request.getParameter("pagenum"));
		}
		
		int total = toupiaoDao.selectBeanCount(where.replaceAll("order by id desc", ""));
		
		request.setAttribute("toupiaolist", toupiaoDao.selectBeanList((currentpage - 1)* pagesize, pagesize, where));
		
		request.setAttribute("pagerinfo", Pager.getPagerNormal(total, pagesize,currentpage, "indexmethod!toupiaolist", "共有" + total + "条记录"));

		this.setUrl("toupiaolist.jsp");
		return SUCCESS;
	}
	
	
	
	//图表统计
	public String renlist3() throws IOException {
		HttpServletRequest request = this.getRequest();
		
		
		String zid = request.getParameter("zid");
		
		request.setAttribute("zid", zid);
		
		Zhuti zhuti = zhutiDao.selectBean(" where id= "+zid);
		
		request.setAttribute("zhuti", zhuti);
		
		StringBuffer sb = new StringBuffer();
		sb.append(" where ");

		
		
		
		sb.append("   deletestatus=0  and zhuti.id="+zid+"  order by shu desc ");
		String where = sb.toString();

		List<Ren> renlist = renDao.selectBeanList(0, 9999, where);
	

	
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();

		for(Ren bean:renlist){
			dataset.addValue(bean.getShu(), bean.getXingming(),bean.getXingming());
		}

	
		

		JFreeChart chart = ChartFactory.createBarChart3D(null, "候选人姓名",
				"票数", dataset, PlotOrientation.VERTICAL, true, false, false);

		//柱状图(CategoryPlot):   
		CategoryPlot plot = chart.getCategoryPlot();
		//获取图表区域对象   
		CategoryAxis domainAxis = plot.getDomainAxis();
		//水平底部列表    
		domainAxis.setLabelFont(new Font("黑体", Font.BOLD, 14));
		//水平底部标题    
		domainAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 12));
		//垂直标题    
		ValueAxis rangeAxis = plot.getRangeAxis();
		//获取柱状    
		rangeAxis.setLabelFont(new Font("黑体", Font.BOLD, 15));
		chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));

		String s = new StringBuilder().append(new Date().getTime()).toString();
		request.setAttribute("time", s);

		String savaPath = ServletActionContext.getServletContext().getRealPath(
				"/")
				+ "/uploadfile/" + s + ".png";

		ChartUtilities.saveChartAsPNG(new File(savaPath), chart, 900, 360);
		

		request.setAttribute("title", "图表统计");
		
		this.setUrl("renlist3.jsp");
		
		return SUCCESS;

	}
	
}
